﻿using HybridCLR.Editor.Settings;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using Debug = UnityEngine.Debug;
internal static class ScriptUpdate
{
    private const string buildPackage = "buildPackage.txt";

    private static readonly string[] hotUpdateFolders = new string[] 
    {
        "Assets/HotUpdate"
    };

    public static bool Check()
    {
        if (!File.Exists(buildPackage))
            return true;

        var curHash = Shell.Run("git", "rev-parse HEAD").Trim();
        var oldHash = File.ReadAllText(buildPackage);
        var result = Shell.Run("git",$"diff --stat --name-only {curHash} {oldHash}");
        var lines = result.Split('\n').Where(x => x.EndsWith(".cs"));

        HashSet<string> hotUpdateScirpt = new HashSet<string>();
        foreach (var folder in hotUpdateFolders)
        {
            foreach(var script in Directory.GetFiles(folder, "*.cs"))
            {
                if (!hotUpdateScirpt.Contains(script))
                    hotUpdateScirpt.Add(script.Replace("\\","/"));
            }
        }

        List<string> scriptChanged = new List<string>();
        foreach (var line in lines)
        {
            if (line.IndexOf("/Editor/") != -1)
                continue;
            if(!hotUpdateScirpt.Contains(line))
            {
                scriptChanged.Add(line);
            }
        }

        if(scriptChanged.Count > 0)
        {
            Debug.LogError($"非热更层有改动重新打包!\n{string.Join("\n",scriptChanged)}");
            return false;
        }
        Debug.Log("script update check succeed");
        return true;
    }

    public static void UpdateHash()
    {
        var hash = Shell.Run("git", "rev-parse HEAD").Trim();
        File.WriteAllText(buildPackage, hash);
    }

    private static string[] GetFolderScripts(string folder)
    {
        return Directory.GetFiles(folder, "*.cs");
    }
}
